#!/usr/bin/env python

from ftplib import *;
import StringIO, sys, getopt,os,urllib, traceback,re;

FETCHURL = "http://netsupport.tsinghua.edu.cn/mfdzb/freeip.htm"
maxnum = 5
def err_usage():
    print 'usage: %s [-m num_of_news]'%sys.argv[0]
    sys.exit(1)

def changeline(text):
    parent = ""
    playlist = open('playlist.m3u', 'w')
    for line in text.readlines():
        if line.startswith('pub/'):
            parent = line.strip()
            parent = parent.replace('pub/Music/MP3/','http://thu.trueice.net/music/')
        elif line.startswith('\t'):
            playlist.write(parent+'/'+line.strip())
            playlist.write(os.linesep)
    playlist.close()
    
if __name__ == "__main__":
    print "Content-type: text/plain; charset=gb2312\n\n";

    opts, args = getopt.getopt(sys.argv[1:], 'm:')
    for optpair in opts:  # like this[('-d', ''), ('-k', '3')...]
        if optpair[0]=='-m':
            try:
                maxnum = int(optpair[1])
            except:
                err_usage()
            if maxnum ==-1:
                print "can't be -1!"
                sys.exit(1)

    NO_FETCH = False;
        
    orifile = urllib.urlopen(FETCHURL)
    import time
    filename = "".join(["freeip"]+["%02d"%x for x in time.localtime()[:3]]+[".bat"])

    try:    
        try:
            outfile = open(filename)
            # success open?
            print "do you want to overwrite the file '%s'? [y/n]"%filename,
            answer = raw_input()
            outfile.close()
            if answer.lower().find('y')!=-1:
                outfile = open(filename, 'w')
                print 'old file cleared'
            else:
                filename = str(time.localtime()[5])+filename
                outfile = open(filename,'w')
                print 'write to file:"%s" now'%filename
        except IOError:
            outfile = open(filename,'w')
    #        traceback.print_exc()
        
        for line in orifile.readlines():
            line=line.strip()
            mat=re.search('^([.0-9]+)\W+([.0-9]+)\W+([.0-9]+)',line)
            if mat:
                print "route add %s mask %s %s metric 10"%(mat.group(1),
                                                           mat.group(3),
                                                           "192.168.0.1")

    except KeyboardInterrupt:
        outfile.close()
        orifile.close()
